package as;

import as.internal.TabletStatus;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *  Java interface to Wintab
 *
 *  @version $Id: Jwintab.java,v 1.1 2000/01/12 12:31:34 rekimoto Exp rekimoto 
 *  @author rekimoto
 *  @revised David Xu
 *  Log:
 *    10.31.2010 David: add dimension getter
 *    10.30.2010 David: add cursor
 *    1.29.2000 rekimoto: add pressure parameter
 *    1.8.2000  rekimoto:  initial creation
 *
 **/   
public class Jwintab {
	private static boolean hasTablet = false;

    static {
		try {
			InputStream in = Jwintab.class.getResourceAsStream("/as/jwintab.dll");
			String where = System.getProperty("java.io.tmpdir") + "/jwintab.dll";
			OutputStream os = new FileOutputStream(where);
			byte [] buffer = new byte[1024];
			int read;
			while ((read = in.read(buffer)) > 0) {
				os.write(buffer, 0, read);
			}
			in.close();
			os.close();
			System.load(where);
			hasTablet = true;
		} catch (Throwable ex) {}
	}

	private static volatile int[] statusBuffer = new int[10];

    Jwintab(){}

	public static boolean hasTablet() {
		return hasTablet;
	}

	/**
	 * Opens the tablet. The tablet dimensions will be inserted into the supplied array.
	 */
	public static boolean tabletOpen(int [] v) {
		return open(v) == 1;
	}

	/**
	 * Closes the tablet. All native resources allocated for the tablet are released.
	 */
	public static boolean tabletClose() {
		return close() == 1;
	}

    /** returns current version number 
     */
    public static native int getVersion();
    
    private static native int open(int [] v);

	/** call this before closing the application, otherwise tablet does not
	    work.
	**/    
    private static native int close();
    
    /** val[0..5]  = {x, y, button, orientation, angle, pressure}
     */
    public static native int getPacket(int val[]);

	/**
	 * Wrapper for getPacket that supports the TabletStatus structure.
	 */
	public static boolean getPacket(TabletStatus status) {
		int result = getPacket(statusBuffer);
		if (result > 0) {
			status.x = statusBuffer[0];
			status.y = statusBuffer[1];
			status.button = statusBuffer[2];
			status.orientation = statusBuffer[3];
			status.angle = statusBuffer[4];
			status.pressure = statusBuffer[5];
			status.cursor = statusBuffer[6];
			return true;
		}

		return false;
	}

	/**
	 * Overlaps the current context on the windows tablet context stack. This context will be given top priority.
	 */
	public static native boolean overlap();

	/**
	 * Underlaps the current context on the windows tablet context stack. This context will be given less priority.
	 */
	public static native boolean underlap();

}

